import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Equal, Repository, Not, IsNull } from 'typeorm'
import { CreateWorkStateDto } from './dto/create-work-state.dto'
import { UpdateWorkStateDto } from './dto/update-work-state.dto'
import { WorkState } from './entities/work-state.entity'
import { formatOptionData } from 'src/utils'
@Injectable()
export class WorkStateService {
  constructor(
    @InjectRepository(WorkState)
    private readonly workstate: Repository<WorkState>
  ) {}
  create(createWorkStateDto: CreateWorkStateDto) {
    const workState = new WorkState()
    workState.name = createWorkStateDto.name
    workState.desc = createWorkStateDto.desc
    return this.workstate.save(workState)
  }

  async findAll(params: {
    page: number
    pageSize: number
    isDelete?: boolean
  }) {
    const where = {}
    params.isDelete && (where['deleteDate'] = Not(IsNull()))
    const data = await this.workstate.find({
      where: { ...where },
      withDeleted: params.isDelete,
      skip: (params.page - 1) * params.pageSize,
      take: params.pageSize
    })
    const total = await this.workstate.count({
      where: { ...where },
      withDeleted: params.isDelete
    })
    return { data, total }
  }

  async findAllOption() {
    const data = await this.workstate.find()
    return formatOptionData(data)
  }

  async findOne(id: number) {
    return await this.workstate.findOne({
      where: { id: Equal(id) }
    })
  }

  update(id: number, updateWorkStateDto: UpdateWorkStateDto) {
    return this.workstate.update(id, updateWorkStateDto)
  }

  remove(ids: number[]) {
    return this.workstate.softDelete(ids)
  }

  restore(ids: number[]) {
    return this.workstate.restore(ids)
  }
}
